<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .w {
            width: 1200px;
            margin: 0 auto;
        }

        .header {
            margin-bottom: 20px;
            height: 200px;
            background-color: pink;
        }

        .content {
            margin-bottom: 20px;
            height: 500px;
            background-color: blue;
        }

        .content-hd {
            margin-bottom: 20px;
            height: 300px;
            background-color: yellow;
        }

        .footer {
            margin-bottom: 20px;
            height: 800px;
            background-color: green;
        }

        .right-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            right: 30px;
            background-color: pink;
        }

        .right-nav ul li {
            list-style: none;
            padding: 5px 10px;
        }

        a {
            display: block;
            width: 28px;
            text-decoration: none;
            color: #666;
            font-size: 14px;
        }

        .go-back {
            display: none;
        }
    </style>
</head>

<body>
    <div class="header w"></div>
    <div class="content w"></div>
    <div class="content-hd w"></div>
    <div class="footer w"></div>
    <div class="right-nav">
        <ul>
            <li><a href="#">爱逛淘宝</a></li>
            <li><a href="#">爱逛淘宝</a></li>
            <li><a href="#">爱逛淘宝</a></li>
            <li class="go-back"><a href="javascript:;">返回顶部</a></li>
            <li><a href="#">爱逛淘宝</a></li>
            <li><a href="#">爱逛淘宝</a></li>
        </ul>
    </div>
    <script>
        var header = document.querySelector('.header');
        var rightNav = document.querySelector('.right-nav');
        var goBack = document.querySelector('.go-back');
        var contentHd = document.querySelector('.content-hd');
        var topAb = rightNav.offsetTop;
        document.addEventListener('scroll', function () {
            //window.pageYOffset 页面被卷去的头部 I9以上支持 与 document.documentElement.scrollTop(老版本支持还要条件声明DTD)
            if (window.pageYOffset >= header.offsetHeight) {
                rightNav.style.position = 'fixed';
                rightNav.style.top = topAb - header.offsetHeight + 'px';
            } else {
                rightNav.style.position = 'absolute';
                rightNav.style.top = topAb + 'px';
            }
            if (window.pageYOffset >= contentHd.offsetTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }
        });
    </script>
</body>

</html>